<template>
	<div class="vue_app GoodsForSF" style="position: relative;width: 100%;" @click="openApp">
		<m-header v-if="!isApp && !isShare"  :title="Title" :hasTitle="true" :hasBack="true" :hasCart="true">
			<Share :url="shareUrl()" style="right: 3rem;"></Share>
		</m-header>
		<div class="overhid" :style="`height: ${screenHeight}px`">
			<vertical-scroll ref='verticalScroll' :bounce="true">
				<content-container :style="`background-color: ${Bgcolor}`">
					<!--<user-card v-for="(item, index) in pageTree.content[type.userCard]" :key="index+'sfuserCard'" v-sdrag:real="{id: item.id, com: item.id, type: type.userCard, editable:false}">
					</user-card>-->
					<HomeCarousel :list="dataStore[item.type][item.id] || []" :bannerid="item.id" v-for="(item, index) in pageTree.content[type.HomeCarousel]" v-sdrag:real="{id: item.id, com: item.id, type: type.HomeCarousel}" :key="index + 'carousel'">
					</HomeCarousel>

					<activitiesbanner :list="dataStore[item.type][item.id] || []" :bannerid="item.id" v-for="(item, index) in pageTree.content[type.activitiesbanner]" :key="index+'sfbanner'" v-sdrag:real="{id: item.id, com: item.id, type: type.activitiesbanner}">
					</activitiesbanner>

					<new-zone :list="dataStore[item.type][item.id] || []" v-for="(item, index) in pageTree.content[type.NewZone]" :key="index+'sfNewZone'" v-sdrag:real="{id: item.id, com: item.id, type: type.NewZone}">
					</new-zone>

					<activities-three-pic :list="dataStore[item.type][item.id] || []" v-for="(item, index) in pageTree.content[type.activitiesThreePic]" :key="index+'sfThreePic'" v-sdrag:real="{id: item.id, com: item.id, type: type.activitiesThreePic}">
					</activities-three-pic>

					<activities-slide-pic :list="dataStore[item.type][item.id] || []" v-for="(item, index) in pageTree.content[type.activitiesSlidePic]" :key="index+'sfSlidePic'" v-sdrag:real="{id: item.id, com: item.id, type: type.activitiesSlidePic}">
					</activities-slide-pic>

					<activities-new-bot :list="dataStore[item.type][item.id] || []" v-for="(item, index) in pageTree.content[type.activitiesNewBot]" :key="index+'sfNewBot'" v-sdrag:real="{id: item.id, com: item.id, type: type.activitiesNewBot}">
					</activities-new-bot>

					<activities-two-pro :list="dataStore[item.type][item.id] || []" :twoproid="item.id" v-for="(item, index) in pageTree.content[type.activitiesTwoPro]" :key="index+'sfTwoPro'" v-sdrag:real="{id: item.id, com: item.id, type: type.activitiesTwoPro}">
					</activities-two-pro>

					<activities-one-pro :list="dataStore[item.type][item.id] || []" :oneproid="item.id" v-for="(item, index) in pageTree.content[type.activitiesOnePro]" :key="index+'sfOnePro'" v-sdrag:real="{id: item.id, com: item.id, type: type.activitiesOnePro}">
					</activities-one-pro>

					<activities-nine-pro :list="dataStore[item.type][item.id] || []" v-for="(item, index) in pageTree.content[type.activitiesNinePro]" :key="index+'sfNinePro'" v-sdrag:real="{id: item.id, com: item.id, type: type.activitiesNinePro}">
					</activities-nine-pro>

					<activitie-coupons :list="dataStore[item.type][item.id] || []" :copolddata='copolddata' :couponsid="item.id" v-for="(item, index) in pageTree.content[type.ActivitieCoupons]" :key="index+'sfCoupons'" v-sdrag:real="{id: item.id, com: item.id, type: type.ActivitieCoupons}">
					</activitie-coupons>

					<activitie-coupons2 :list="dataStore[item.type][item.id] || []" :copolddata='copolddata' :couponsid="item.id" v-for="(item, index) in pageTree.content[type.ActivitieCoupons2]" :key="index+'sfCoupon'" v-sdrag:real="{id: item.id, com: item.id, type: type.ActivitieCoupons2}">
					</activitie-coupons2>
					<GuessYouLike :guessYouLikeid="item.id" v-for="(item, index) in pageTree.content.GuessYouLike" v-sdrag:real="{id: item.id, com: item.id, type: type.GuessYouLike,editable:false}" :key="index+'acYouLike'">
					</GuessYouLike>
				</content-container>
			</vertical-scroll>
		</div>
		<button-to-top @goTop="goTop"></button-to-top>
		<add-cart-animate></add-cart-animate>
	</div>
</template>
<script>
	//引用包裹“真实-基础组件”的组件
	import ContentContainer from "../../components/ContentContainer";
	import VerticalScroll from '../../components/VerticalScroll';
	import ButtonToTop from '../../components/ButtonToTopForTest';
	import AddCartAnimate from "../../components/AddCartAnimate";
	//引用真实-基础组件
	import Header from "../header";
	/*import UserCard from "./UserCard";*/
	import NewZone from "./NewZone";
	import activitiesbanner from "./activitiesbanner";
	import activitiesThreePic from "./threePic";
	import activitiesSlidePic from "./slidePic";
	import activitiesNewBot from "./NewBot";
	import activitiesTwoPro from "./TwoPro";
	import activitiesOnePro from "./OnePro";
	import activitiesNinePro from "./NinePro";
	import GuessYouLike from "./GuessYouLike";
	import ActivitieCoupons from "./Coupons";
	import ActivitieCoupons2 from "./Coupons2";
	import HomeCarousel from "./Carousel";
	//引用util文件
	import { getPageTree, initDomTree } from "../../utils/getPageTree";
	import getPageName from "../../utils/getPageName";
	import axios from "axios";
	import Share from "../../components/Share";
	import { CHANGE_NAVIGATION } from "../../config/postMessage-types";
	export default {
		data() {
			return {
				type: {

					NewZone: "NewZone",
					activitiesbanner: "activitiesbanner",
					activitiesThreePic: "activitiesThreePic",
					activitiesSlidePic: "activitiesSlidePic",
					activitiesNewBot: "activitiesNewBot",
					activitiesTwoPro: "activitiesTwoPro",
					activitiesOnePro: "activitiesOnePro",
					activitiesNinePro: "activitiesNinePro",
					GuessYouLike: "GuessYouLike",
					HomeCarousel: "HomeCarousel",
					ActivitieCoupons: 'ActivitieCoupons',
					ActivitieCoupons2: 'ActivitieCoupons2',
				},
				dataStore: {
					NewZone: {},
					activitiesbanner: {},
					activitiesThreePic: {},
					activitiesSlidePic: {},
					activitiesNewBot: {},
					activitiesTwoPro: {},
					activitiesOnePro: {},
					activitiesNinePro: {},
					HomeCarousel: {},
					ActivitieCoupons: {},
					ActivitieCoupons2: {},
				}, //缓存所有数据的对象
				Bgcolor: "",
				Title: "",
				//顶部大海报数据
				bannerdata: [],
				bannerdataid: "",
				//新人专区
				NewZone: [],
				NewZoneid: "",
				//三张图片
				threePicData: [],
				threePicid: "",
				//可滑动图片
				slidePicData: [],
				slidePicid: "",
				//新人专区底部
				NewBotData: [],
				NewBotid: "",
				//一排两个商品信息
				TwoProData: [],
				TwoProid: "",
				//独个商品
				OneProData: [],
				OneProid: "",
				//九宫格商品
				NineProData: [],
				NineProid: "",
				//优惠券信息
				CouponsData: [],
				Couponsid: "",
				//判断是否为分享的页面
				Share: 0,
				//优惠券的实时更新信息
				copolddata: {},
				flagfresh: true
			}
		},
		computed: {
			pageName() {
				return getPageName();
			},
			pageTree() {
				return getPageTree(this);
			},
			pageConfig() {
				return getPageTree(this, this.pageName).config;
			},
			screenHeight() {
				if(!this.isApp && !this.isShare) {
					return window.innerHeight - '60';
				} else {
					return window.innerHeight - '0';
				}
			},
			env() {
				return window.environment;
			},
			isApp() {
				if(window.isApp){
					return window.isApp;
				}else{
					return false
				}
			},
			isShare(){
				if(this.Share == 1) {
					return true;
				} else {
					return false;
				}
			}
		},
		methods: {
			openApp(){
				if (this.$route.query.share==='1') {
					this.$router.push({name: "MiddleWare"});
				}
			},
			//引入rn头部
			chanceNavigation(data) {
				let baseUrl = `https://${location.hostname}/static/NJ/rnweb/index.html#/${this.$router.currentRoute.path.slice(1)}?share=1`;
				let titleConfig = JSON.stringify({
					type: CHANGE_NAVIGATION,
					params: {
						title: data,
						page: 'Activity',
						shareOptions: {
							"title": '宁家商城新品上市',
							"content": `钜惠${new Date().getMonth() + 1}月，宁家商城全新升级，一路嗨翻天`,
							"url": baseUrl,
							"imageurl": ""
						},
					}
				});
				window.postMessage(titleConfig);
			},
			//回到顶部
			goTop() {
				this.$refs.verticalScroll.goTop()
			},
			getsessionIddata() {
				this.sessionIddata = localStorage.getItem('sessionId');
				this.storeCodedata = localStorage.getItem('storeCode');
				if(this.pageConfig) {
					this.Bgcolor = this.pageConfig.activitiesBgcolor;
					this.Title = this.pageConfig.activitiesTitle;
				}
			},
			queryallBanner(id) {
				let url = window.api.goods_host + window.api.home_ad;
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.HomeCarousel][id] = data.data.data[0] ? data.data.data[0][id] : []))
						//缓存到本地
						this.initCache();
					}
				})
			},
			//顶部大海报数据
			queryBanner(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/posters';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.activitiesbanner][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getBannerlist(id) {
				this.bannerdataid = id
				return this.bannerdata[`${id}`]
			},*/
			//新人专区
			queryNewZone(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/newborn';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.NewZone][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getNewZonelist(id) {
				this.NewZoneid = id
				return this.NewZone[`${id}`]
			},*/
			//三张图片
			querythreePic(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/three_pic';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.activitiesThreePic][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getthreePiclist(id) {
				this.threePicid = id
				return this.threePicData[`${id}`]
			},*/
			//可滑动图片
			queryslidePic(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/slide_pic';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.activitiesSlidePic][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getslidePiclist(id) {
				this.slidePicid = id
				return this.slidePicData[`${id}`]
			},*/
			//新人专区底部
			queryNewBot(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/new_bot';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.activitiesNewBot][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getNewBotlist(id) {
				this.NewBotid = id
				return this.NewBotData[`${id}`]
			},*/
			//一排两个商品
			queryTwoPro(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/two_pro';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id,
						usePlatform: "wap",
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.activitiesTwoPro][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getTwoProlist(id) {
				this.TwoProid = id
				return this.TwoProData[`${id}`]
			},*/
			//独个商品
			queryOnePro(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/one_pro';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id,
						usePlatform: "wap",
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.activitiesOnePro][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getOneProlist(id) {
				this.OneProid = id
				return this.OneProData[`${id}`]
			},*/
			//九宫格商品
			queryNinePro(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/nine_pro';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id,
						usePlatform: "wap",
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.activitiesNinePro][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getNineProlist(id) {
				this.NineProid = id
				return this.NineProData[`${id}`]
			},*/
			//优惠券信息
			queryCoupons(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/act_coup';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id,
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.ActivitieCoupons][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			/*getCouponslist(id) {
				this.Couponsid = id
				return this.CouponsData[`${id}`]
			},*/
			queryCoupons2(id) {
				let url = window.api.goods_host + '/resourceConfig/mobile/activities_pic_coupons';
				let options = {
					method: "get",
					url,
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
						relGroup: id,
					},
				}
				axios(options).then(data => {
					if(data.data.data) {
						this.dataStore = Object.assign({}, this.dataStore,
							(this.dataStore[this.type.ActivitieCoupons2][id] = data.data.data[0] ? data.data.data[0][id] : []))
						this.initCache()
					}
				})
			},
			//优惠券信息对比
			queryCoupons3() {
				var sessionId = localStorage.getItem('sessionId');
				let url = api.trade_host + '/marketCenter/getDiffReleasedCoupons/' + api.enterpriseCode;
				let config = {
					url: url,
					method: 'GET',
					headers: {
						'sessionId': sessionId,
					},
				};
				axios(config).then((res) => {
					this.copolddata = res.data.data[0]
				})
			},
			//初始化监听数据变化
			inite() {
				PSEvent.listen("changeStoreCode", () => {
					this.getsessionIddata();
					this.initData();
					/*this.queryBanner()
					this.queryNewZone()
					this.querythreePic()
					this.queryslidePic()
					this.queryNewBot()
					this.queryTwoPro()
					this.queryOnePro()
					this.queryNinePro()*/
				});
				PSEvent.listen("bannerUpdate", () => {
					this.initData();
				});
				PSEvent.listen("postersUpdate", () => {
					/*this.queryBanner()*/
					this.initData();
				});
				PSEvent.listen("newZoneUpdate", () => {
					/*this.queryNewZone()*/
					this.initData();
				});
				PSEvent.listen("threePicUpdate", () => {
					/*this.querythreePic()*/
					this.initData();
				});
				PSEvent.listen("slidePicUpdate", () => {
					/*this.queryslidePic()*/
					this.initData();
				});
				PSEvent.listen("NewBotUpdate", () => {
					/*this.queryNewBot()*/
					this.initData();
				});
				PSEvent.listen("TwoProUpdate", () => {
					/*this.queryTwoPro()*/
					this.initData();
				});
				PSEvent.listen("OneProUpdate", () => {
					/*this.queryOnePro()*/
					this.initData();
				});
				PSEvent.listen("NineProUpdate", () => {
					/*this.queryNinePro()*/
					this.initData();
				});
				PSEvent.listen("CouponsUpdate", () => {
					/*this.queryCoupons()*/
					this.initData();
				});
				PSEvent.listen("CouponsUpdate2", () => {
					/*this.queryCoupons()*/
					this.initData();
				});
				PSEvent.listen("BgcolorUpdate", () => {
					this.getsessionIddata()
				});
			},
			removeListen() {
				PSEvent.remove("changeStoreCode");
				PSEvent.remove("postersUpdate");
				PSEvent.remove("newZoneUpdate");
				PSEvent.remove("threePicUpdate");
				PSEvent.remove("slidePicUpdate");
				PSEvent.remove("NewBotUpdate");
				PSEvent.remove("TwoProUpdate");
				PSEvent.remove("BgcolorUpdate");
				PSEvent.remove("OneProUpdate");
				PSEvent.remove("NineProUpdate");
				PSEvent.remove("bannerUpdate");
				PSEvent.remove("CouponsUpdate");
				PSEvent.remove("CouponsUpdate2");
				PSEvent.remove("dataRefresh", this.dataRefresh);
			},

			initData() {
				//第一步拿到所有的id
				let requestData = [];
				for(let key in this.pageTree.content) {
					this.pageTree.content[key].forEach((item) => {
						requestData.push({
							id: item.id,
							type: item.type,
							state: 1
						});
					});
				}
				requestData.forEach(item => {
					this.startQueryData(item);
				});
			},
			//开始根据type和id值去请求对应的数据
			startQueryData(component) {
				switch(component.type) {
					case this.type.NewZone:
						this.queryNewZone(component.id);
						break;
					case this.type.activitiesbanner:
						this.queryBanner(component.id);
						break;
					case this.type.activitiesThreePic:
						this.querythreePic(component.id);
						break;
					case this.type.activitiesSlidePic:
						this.queryslidePic(component.id);
						break;
					case this.type.activitiesNewBot:
						this.queryNewBot(component.id);
						break;
					case this.type.activitiesTwoPro:
						this.queryTwoPro(component.id);
						break;
					case this.type.activitiesOnePro:
						this.queryOnePro(component.id);
						break;
					case this.type.activitiesNinePro:
						this.queryNinePro(component.id);
						break;
					case this.type.ActivitieCoupons:
						this.queryCoupons(component.id);
						break;
					case this.type.ActivitieCoupons2:
						this.queryCoupons2(component.id);
						break;
					case this.type.HomeCarousel:
						this.queryallBanner(component.id);
						break;
					default:
						break;
				}
			},
			//把活动页数据缓存到本地
			initCache() {
				/*localforage.setItem(this.$route.name.toString(), this.dataStore);
				this.$refs.verticalScroll && this.$refs.verticalScroll.refresh();*/
			},
			//根据本地是否有缓存来决定去请求接口与否
			async loadData() {
				this.initData();
				/*if(await localforage.getItem(this.$route.name.toString()) && this.env == 'production') {
					this.dataStore = await localforage.getItem(this.$route.name.toString());
					this.initData();
				} else {
					this.initData();
				}*/
			},
			//分享链接
			shareUrl() {
				/*let str = JSON.stringify(location.href + '&share=1');*/
				return `${location.href}?share=1`;
			},
			//上拉刷新
			dataRefresh() {
				if(this.flagfresh) {
					this.flagfresh = false
					this.getsessionIddata();
					this.initData();
					this.queryCoupons3();
				}

				setTimeout(() => {
					this.flagfresh = true
					window.PSEvent.trigger('pageLoadedOver')
				}, 1200)
			},
		},
		components: {
			"m-header": Header,
			ContentContainer,
			/*UserCard,*/
			activitiesbanner,
			NewZone,
			activitiesThreePic,
			activitiesSlidePic,
			activitiesNewBot,
			activitiesTwoPro,
			activitiesNinePro,
			activitiesOnePro,
			"vertical-scroll": VerticalScroll,
			ButtonToTop,
			AddCartAnimate,
			GuessYouLike,
			Share,
			ActivitieCoupons,
			ActivitieCoupons2,
			HomeCarousel
		},
		created() {
			window.PSEvent.listen('dataRefresh', this.dataRefresh)
		},
		mounted() {
			
			
			this.Share = this.$route.query.share;
			this.queryCoupons3();
			this.inite();
			initDomTree(this.$store.getters.getDomTree[this.pageName]);
			this.getsessionIddata()
			this.loadData();
			if(this.isShare && this.Title) {
				document.getElementsByTagName("title")[0].innerText = this.Title
			}
			if(this.isApp) {
				this.chanceNavigation('')
			}
		},
		updated() {
			//console.log(`this.$store.getters.getDomTree[${this.pageName}]`, this.$store.getters.getDomTree[this.pageName])
			initDomTree(this.$store.getters.getDomTree[this.pageName]);
			this.$nextTick(() => {
				setTimeout(() => {
					this.$refs.verticalScroll && this.$refs.verticalScroll.refresh();
				}, 500)
			});
		},
		beforeDestroy() {
			this.removeListen()
		},
		watch: {
			Title(data) {
				if(data && !this.changeNavigationState && this.isApp) {
					this.changeNavigationState = true;
					this.chanceNavigation(data)
				}
			}
		},
		beforeRouteLeave(to, from, next) {
			var name = from.name;
			this.$store.commit('cjy/SET_RETURN_POS', name);
			next();
		},
	}
</script>
<style>
	.overhid {
		overflow: hidden;
	}
	
	.GoodsForSF {
		-webkit-overflow-scrolling: touch;
	}
	
	.GoodsForSF .cjy-center {
		top: 0px !important;
	}
</style>